<script setup lang="ts">
  import { computed } from 'vue';
  import { useLowcodeStore } from '@/store/features/lowcode';
  import { storeToRefs } from 'pinia';
  import type { ComponentInstance } from '@/types/lowcode';
  import Input from './childComponents/Input.vue';
  import Select from './childComponents/Select.vue';
  const lowcodeStore = useLowcodeStore();
  const { canvasComponents, selectedComponentId } = storeToRefs(lowcodeStore);

  // 获取组件列表
  const getCanvasComponents = computed<ComponentInstance[]>(() => canvasComponents.value);
  // 获取选中的组件Id
  const getSelectedComponentId = computed(() => selectedComponentId.value);

  // 组件类型映射
  const componentMap = {
    input: Input,
    select: Select,
  };

  const getComponentByType = (type: string) => {
    return componentMap[type as keyof typeof componentMap] || 'div';
  };

  const handleDragOver = () => {
    // 允许拖拽
  };
  // 放手触发
  const handleDrop = (e: DragEvent) => {
    const componentData = JSON.parse(e.dataTransfer!.getData('application/json'));
    // 在鼠标位置创建组件实例
    lowcodeStore.addComponentInstance({
      id: `${componentData.id}-${Date.now()}`,
      type: componentData.type,
      props: componentData.defaultProps || {},
      x: e.offsetX - 100,
      y: e.offsetY - 50,
      width: componentData.type === 'card' ? 300 : 200,
      height: componentData.type === 'card' ? 200 : 50,
    });
  };
  const handleComponentClick = (id: string) => {
    lowcodeStore.setSelectedComponentId(id);
  };
  const handleCanvasClick = () => {
    lowcodeStore.setSelectedComponentId(null);
  };
</script>
<template>
  <div
    class="component-canvas"
    @dragover.prevent="handleDragOver"
    @drop.prevent="handleDrop"
    @click="handleCanvasClick"
  >
    <div class="component-container">
      <div
        v-for="item in getCanvasComponents"
        :key="item.id"
        :class="['component-instance', { active: item.id === getSelectedComponentId }]"
        :style="{
          position: 'absolute',
          left: `${item.x}px`,
          top: `${item.y}px`,
          width: `${item.width}px`,
          height: `${item.height}px`,
        }"
        @click.stop="handleComponentClick(item.id)"
      >
        <!--动态渲染组件类型 -->
        <component :is="getComponentByType(item.type)" v-bind="item.props"></component>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  .component-canvas {
    flex: 1;
    height: 100%;
    background-color: #f5f5f5;
    position: relative;
    overflow: auto;
    .component-container {
      width: 1200px;
      height: 800px;
      background-color: white;
      margin: 20px auto;
      position: relative;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
      .component-instance {
        box-sizing: border-box;
        padding: 8px;
        cursor: move;
        &.active {
          outline: 2px solid #409eff;
          border-radius: 4px;
        }
      }
    }
  }
</style>
